package model

import (
	"vueBasic/app/admin/filter"
	"vueBasic/global"
)

var ArticleCateM = new(articleCateModel)

type articleCateModel struct {
	Id         uint   `form:"id" json:"id"`
	Title      string `form:"title" json:"title"` //标题
	Pid        int    `form:"pid" json:"pid"`
	Sort       int    `form:"sort" json:"sort"`
	Keywords   string `form:"keywords" json:"keywords"`
	Desc       string `form:"desc" json:"desc"`
	AddTime    int64  `form:"add_time" json:"add_time"`
	UpdateTime int64  `form:"update_time" json:"update_time"`
}

func (*articleCateModel) TableName() string {
	return global.CONF.Database.Db.Prefix + "article_cate"
}

func (*articleCateModel) GetList(req *filter.ArticleCateReq) ([]articleCateModel, int64, error) {
	var (
		articleCateList []articleCateModel
		count           int64
	)
	query := global.DB.Model(&articleCateModel{})
	if err := query.Limit(req.Limit).Offset((req.Page - 1) * req.Limit).Order("sort ASC").Find(&articleCateList).Error; err != nil {
		return nil, 0, err
	}
	//获取总条数
	query.Count(&count)
	return articleCateList, count, nil
}

func (*articleCateModel) Add(req *filter.ArticleCateAddReq) (uint, error) {
	entity := articleCateModel{}
	entity.Title = req.Title
	entity.Pid = 0
	entity.Sort = req.Sort
	entity.Keywords = req.Keywords
	entity.Desc = req.Desc
	entity.AddTime = req.AddTime
	entity.UpdateTime = req.UpdateTime
	if err := global.DB.Create(&entity).Error; err != nil {
		return 0, err
	}
	return entity.Id, nil
}

func (*articleCateModel) GetArticleCateById(id int) (*articleCateModel, error) {
	entity := articleCateModel{}
	if err := global.DB.Where("id=?", id).Limit(1).First(&entity).Error; err != nil {
		return nil, err
	}
	return &entity, nil
}

func (*articleCateModel) Update(req *filter.ArticleCateUpdateReq) (uint, error) {
	entity := articleCateModel{Id: req.Id}
	global.DB.First(&entity)
	entity.Title = req.Title
	entity.Sort = req.Sort
	entity.Keywords = req.Keywords
	entity.Desc = req.Desc
	entity.UpdateTime = req.UpdateTime
	if err := global.DB.Save(&entity).Error; err != nil {
		return 0, err
	}
	return entity.Id, nil
}

func (*articleCateModel) UpdateExt(req map[string]interface{}) error {
	query := global.DB.Model(&articleCateModel{})
	if err := query.Where("id=?", req["id"]).Updates(req).Error; err != nil {
		return err
	}
	return nil
}

func (*articleCateModel) Delete(ids []string) (uint, error) {
	query := global.DB.Where("id IN ?", ids)
	err := query.Delete(&articleCateModel{}).Error
	if err != nil {
		return 0, err
	}
	return 1, nil
}

func (*articleCateModel) GetFieldList(field string) ([]*articleCateModel, error) {
	var list []*articleCateModel
	query := global.DB.Model(&articleCateModel{})
	if err := query.Select(field).Order("sort DESC").Scan(&list).Error; err != nil {
		return nil, err
	}
	return list, nil
}
